package com.jmb.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jmb.api.common.exception.LeaseException;
import com.jmb.api.common.result.ResultCodeEnum;
import com.jmb.api.common.utils.ValidUtil;
import com.jmb.api.model.entity.Role;
import com.jmb.api.service.RoleService;
import com.jmb.api.mapper.RoleMapper;
import com.jmb.api.vo.role.RoleVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author jinbo
* @description 针对表【role】的数据库操作Service实现
* @createDate 2025-04-06 21:37:43
*/
@Service
@Transactional(rollbackFor = LeaseException.class)
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
    implements RoleService{
    @Autowired
    private ValidUtil validUtil;
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public void createRole(RoleVo roleVo) {
        // 前置校验
        cheRoleName(roleVo);
        Role role = new Role();
        BeanUtils.copyProperties(roleVo,role);
        this.save(role);
    }

    @Override
    public IPage<RoleVo> getRoleListByQuery(IPage<RoleVo> page, RoleVo roleVo) {
        return roleMapper.pageRoleByQuery(page,roleVo);
    }

    @Override
    public void updateRole(RoleVo roleVo) {
        cheRoleName(roleVo);
        Role role = new Role();
        BeanUtils.copyProperties(roleVo,role);
        LambdaUpdateWrapper<Role> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Role::getRoleId,roleVo.getId());
        roleMapper.update(role,updateWrapper);
    }


    private void cheRoleName(RoleVo roleVo) {
        validUtil.checkName(roleVo.getRoleName(),"角色名称不能为空");
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Role::getRoleName,roleVo.getRoleName());
        if (roleVo.getId()!=null){
            wrapper.ne(Role::getRoleId,roleVo.getId());
        }
        Long count = roleMapper.selectCount(wrapper);
        if (count>0){
            throw new LeaseException(ResultCodeEnum.WEB_API_ROLE_NAME_EXIST);
        }
    }
}




